package com.jx.driving.protocol.terminal.codec;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * 处理不定长list对象
 * 
 * @author shenliuyang
 *
 *         2016年8月12日下午5:35:53
 */
public class ListReaderWriter extends FieldReaderWriter {

    private ClassReaderWriter rw;

    public ListReaderWriter(Field field, int size, int order) {
	super(field, size, order);
	Type type = field.getGenericType();
	if (!(type instanceof ParameterizedType)) {
	    throw new IllegalArgumentException("field not parameterized " + field);
	}
	ParameterizedType pt = (ParameterizedType) type;
	try {
	    rw = new ClassReaderWriter((Class<?>) pt.getActualTypeArguments()[0]);
	} catch (Exception e) {
	    throw new RuntimeException(e);
	}
    }

    @Override
    public void read(InputStream in, Object to) throws IOException {
	List<Object> list = new ArrayList<>();
	while (in.available() != 0) {
	    Object obj;
	    try {
		obj = rw.read(in);
		list.add(obj);
	    } catch (Exception e) {
		throw new RuntimeException(e);
	    }
	}
	wrtietoField(to, list);
    }

    @Override
    public void write(OutputStream out, Object from) throws IOException {
	List<?> list = (List<?>) readFromField(from);
	if (list == null) {
	    return;
	}
	for (Object bean : list) {
	    try {
		rw.write(out, bean);
	    } catch (Exception e) {
		throw new RuntimeException(e);
	    }
	}
    }

}
